using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Principal;
using Com.queryzer2.Dao.Interface;
using Com.queryzer2.Domain.Entities;
using Com.queryzer2.Services.Base;
using Com.queryzer2.Services.Impl;


namespace Com.queryzer2.Security
{
    public interface ISecurityProvider
    {
        MyPrincipal BuildNewIdentity(string username, string password, string type);
        void ChangePassword(string newPassword, decimal id);
    }
   
    public class SecurityProvider:BaseClassic, ISecurityProvider
    {
        public MyPrincipal BuildNewIdentity(string username, string password, string type)
        {

            UtenteEntity ut = base.DbProvider.DaoImpl.UtenteDao.findByUserName(username);
            //UtenteEntity ut1 = ServiceFactory.OracleProvider.DaoImpl.UtenteDao.findByUserName(username);
            if (ut == null) return null;
            if (ut.Password != password) return null;
            string[] roles = new string[3] { "NULL", "NULL", "NULL" };
            
            if (ut.RoleC)
                roles[0] = "COM";
            if (ut.RoleV)
                roles[1] = "VEN";
            if (ut.IsAdmin)
                roles[2] = "ADMIN";

            MyIdentity id = new MyIdentity(username, password, type);
            id.UserID = ut.Id;
            MyPrincipal mp = new MyPrincipal(id, roles);
            return mp;
        }

        public void ChangePassword(string newPassword,decimal id)
        {
            UtenteEntity e = base.DbProvider.DaoImpl.UtenteDao.GetById(id);
            if (e != null)
            {
                e.Password = newPassword;
                base.DbProvider.DaoImpl.UtenteDao.Update(e);
            }
        }
    }
}
